import 'package:flutter_admin/api/odoo/mrp_production_check_odoo_api.dart';
import 'package:flutter_admin/models/odoo/mrp_production.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

import 'mrp_production_check_dialog.dart';
import 'mrp_workorder_list.dart';

class MrpProductionCheckList extends StatefulWidget {
  MrpProductionCheckList({Key? key}) : super(key: key);

  @override
  _MrpProductionCheckListState createState() => _MrpProductionCheckListState();
}

class _MrpProductionCheckListState extends State<MrpProductionCheckList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  MrpProduction mrpProduction = MrpProduction();
  List<MrpProduction> selectedList = [];
  DateFormat format = DateFormat('yyyy-MM-dd');

  @override
  void initState() {
    super.initState();
    mrpProduction.dateStart = Utils.getDate();
    mrpProduction.dateFinished = Utils.getDate();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  stateMap(e) {
    return e == 'confirmed'
        ? '已确认'
        : e == 'progress'
            ? '进行中'
            : e == 'to_close'
                ? '待关闭'
                : e == 'done'
                    ? '完成'
                    : e == 'cancel'
                        ? '已取消'
                        : '--';
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelectDate(
            context,
            width: 180,
            label: '投产开始时间',
            value: mrpProduction.dateStart,
            lastDate: isNotBlank(mrpProduction.dateFinished)
                ? format.parse(mrpProduction.dateFinished!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              mrpProduction.dateStart = v;
              setState(() {});
            },
            onSaved: (v) {
              mrpProduction.dateStart = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '投产结束时间',
            value: mrpProduction.dateFinished,
            firstDate: isNotBlank(mrpProduction.dateStart)
                ? format.parse(mrpProduction.dateStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              mrpProduction.dateFinished = v;
              setState(() {});
            },
            onSaved: (v) {
              mrpProduction.dateFinished = v;
            },
          ),
          CryInput(
            width: 160,
            label: '生产单号',
            value: mrpProduction.name,
            onSaved: (v) {
              mrpProduction.name = v;
            },
          ),
          CryInput(
            width: 160,
            label: '产品名称',
            value: mrpProduction.productName,
            onSaved: (v) {
              mrpProduction.productName = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('生产单号')),
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('产品图号')),
        DataColumn(label: Text('计量单位')),
        DataColumn(label: Text('数量')),
        DataColumn(label: Text('状态')),
      ],
      getCells: (m) {
        MrpProduction mrpProduction = MrpProduction.fromMapCheck(m);
        return [
          DataCell(Text(mrpProduction.name ?? '--')),
          DataCell(Text(mrpProduction.productName ?? '--')),
          DataCell(Text(mrpProduction.productCode ?? '--')),
          DataCell(Text(mrpProduction.productUom ?? '--')),
          DataCell(Text(mrpProduction.productQty != null
              ? mrpProduction.productQty.toString()
              : '--')),
          DataCell(Text(stateMap(mrpProduction.state))),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButton(
          label: "订单明细",
          iconData: Icons.view_headline,
          onPressed: selectedList.length == 1
              ? () => _openDetail(selectedList[0])
              : null,
        ),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _openDetail(MrpProduction mrpProduction) {
    Utils.fullscreenDialog(MrpWorkorderList(mrpProduction: mrpProduction));
  }

  _reset() {
    mrpProduction = MrpProduction();
    formKey.currentState!.reset();
    mrpProduction.dateStart = Utils.getDate();
    mrpProduction.dateFinished = Utils.getDate();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await MrpProductionCheckApi.page(
        data: {"page": page, "domainList": mrpProduction.toDomainListCheck()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: MrpProductionCheckDialog(),
      ),
    ).then((v) {
      if (v != null) {
        mrpProduction = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<MrpProduction>((e) => MrpProduction.fromMapCheck(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.dmsFile) {
          _openDetail(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled: selectedList.length == 1,
            title: Text('产品明细'),
          ),
        ),
      ],
    );
  }
}
